package game.servlet;

import game.util.Game;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.istack.internal.logging.Logger;

/**
 * Servlet implementation class for the user action
 */
@WebServlet("/stepping")
public class SteppingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(Game.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SteppingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // TODO Auto-generated method stub

        Game game = new Game();
        List<Integer> table;
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String param = request.getParameter("param");

        if (param.equalsIgnoreCase("init")) {
            int holeNumber = Integer.parseInt((String) session.getAttribute("hole"));
            int stoneNumber = Integer.parseInt((String) session.getAttribute("stone"));
            table = game.initGameTable(holeNumber, stoneNumber);
            StringBuilder jsonResponse = game.tableToJSon(table, 0);
            logger.info("init json response: " + jsonResponse.toString());

            PrintWriter out = response.getWriter();
            out.print(jsonResponse);
            out.close();

            session.setAttribute("table", table);

        } else {

            table = (List<Integer>) session.getAttribute("table");

            List<String> resList = new ArrayList<String>();

            // user
            int stateAfterStep = game.stepping(table, Integer.parseInt(request.getParameter("param")) - 1,
                    table.size() / 2 - 1);

            StringBuilder jsonResponse = game.tableToJSon(table, stateAfterStep);
            resList.add(jsonResponse.toString());

            // computer
            if (stateAfterStep == 1) {
                // duplicated
                resList.add(jsonResponse.toString());
            }

            if (stateAfterStep == 0 || stateAfterStep == 2) {
                stateAfterStep = game.computerStep(table);
                jsonResponse = game.tableToJSon(table, stateAfterStep);
                resList.add(jsonResponse.toString());
            }
            int compPoints = 0;
            int userPoints = 0;

            for (int i = 0; i < table.size() / 2; i++) {
                userPoints += table.get(i);
            }
            for (int i = table.size() / 2; i < table.size(); i++) {
                compPoints += table.get(i);
            }

            logger.info("user points: " + userPoints);
            logger.info("computer points: " + compPoints);

            // end
            if (stateAfterStep == 3) {

                // computer > user
                // computer win
                if (compPoints > userPoints) {
                    session.setAttribute("winner", "computer");
                    logger.info("computer winner");
                } else {
                    // user win or tie
                    session.setAttribute("winner", "user");
                    logger.info("user winner");

                }
                if (resList.size() < 2) {
                    logger.info("computer stepping isn't exists");
                    resList.add(jsonResponse.toString());
                }
            }

            jsonResponse(response, resList);
            session.setAttribute("table", table);
            session.setAttribute("compPoints", compPoints);
            session.setAttribute("userPoints", userPoints);

        }

    }

    private void jsonResponse(HttpServletResponse response, List<String> resList) throws IOException {
        PrintWriter out = response.getWriter();
        out.print("{\"tableList\":[");
        out.print(resList.get(0));
        out.print(",");
        out.print(resList.get(1));
        out.print("]}");
        out.close();
    }
}
